package Util;

import java.sql.*;

public class JavaUtil01 {
    private static String driver = "com.mysql.jdbc.Driver";//驱动
    private static String url = "jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private static String username = "root";
    private static String password = "root";
    private static Connection con;//链接
    private  static PreparedStatement ps;//预编译sql对象
    private  static ResultSet rs;//结果集对象
//  定义成员变量，有利于全局调用

    //    获取链接
    public static boolean getConn() {
        try{
//            1.加载驱动
            Class.forName(driver);
//            获取链接
            con= DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    //  增删改
    public static  int excuteUpdate(String sql, Object[] params){
        int updateRows=0;//修改的行数
        if (getConn()==true) {
            try {
                PreparedStatement ps = con.prepareStatement(sql);
                for (int i=0;i<params.length;i++){
                  ps.setObject(i+1,params[i]);
                }
                updateRows=ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return updateRows;
    }
    public static  ResultSet excuteQuery(String sql,Object[] params){

        if(getConn()){
            try{
                ps=con.prepareStatement(sql);
                for (int i=0;i<params.length;i++){
                    ps.setObject(i+1,params[0]);
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }

    public static void close() throws SQLException {
        if (ps!=null){
            ps.close();
        }
        if (con!=null){
            con.close();
        }
    }


}
